package com.itheima.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.bean.Employee;
import com.itheima.common.PageParam;
import com.itheima.common.R;
import com.itheima.sevrice.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RequestMapping("/employee")
@RestController
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 登录
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody Employee employee, HttpSession session){
        System.out.println("employee = " + employee);

        Employee loginEmployee = employeeService.login(employee);
        if (loginEmployee !=null){
            //登录成功
            session.setAttribute("employee",loginEmployee);

            return R.success(loginEmployee);
        }
        return R.error("登录失败,用户名或密码失败！");
    }

    /**
     * 退回登录
     * @param session
     * @return
     */
    @PostMapping("/logout")
    public R logout(HttpSession session){
        //让session 失效invalidate()
        session.invalidate();
        return R.success("退出成功！");
    }

    /**
     * 分页查询
     * @param pageParam
     * @return
     */
    @GetMapping("/page")
    public R findPage(PageParam pageParam){
        IPage<Employee> page = employeeService.findPage(pageParam);
        return R.success(page);
    }

    /**
     * 添加员工
     * @param employee
     * @return
     */
    @PostMapping
    public R add(@RequestBody Employee employee){
        //添加员工需要设置默认的初始的密码
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(password);

        int row = employeeService.add(employee);
        if (row>0){
            return R.success("添加员工成功！");
        }
        return  R.error("添加员工失败！");
    }


    /**
     * 修改员工状态
     * @param employee
     * @return
     */
    @PutMapping
    public R update(@RequestBody Employee employee){
        int row = employeeService.update(employee);
        if (row>0){
            return R.success("修改员工状态成功！");
        }
        return R.error("修改员工状态失败！");
    }

    /**
     * 根据员工id 查询员工
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R findById(@PathVariable Long  id){
        Employee e = employeeService.find(id);
        if (e!=null){
            return R.success(e);
        }
        return R.error("查询失败！未找到该员工");
    }

}
